package chu.dejian.ui.fragmet;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.sam.blemodule.R;
import chu.dejian.conf.BLEPreference;
import chu.dejian.dialogOrMenu.DialogManager;
import chu.dejian.entity.RecordEntity;

import com.sam.dejian.ble.fragment.BaseDejianMeasureFragment;
import com.sam.dejian.ble.wrist_bp.MeasureResult;
import com.sam.dejian.ble.wrist_bp.Pressure;
import com.sam.dialog.CustomDialog;
import com.sam.widget.progress.ManometerView;

public class MeasureFragment extends BaseDejianMeasureFragment {
	private static MeasureFragment instance;
	public synchronized static MeasureFragment getInstance(){
		if(instance == null){
			instance = new MeasureFragment();
		}
		return instance;
	}
	enum MEASURE_STATE {READY_TO_MEASURE,STARTING_MEASURE,MEASURING,STOPING_MEASURE,MEASURE_ANOMALOUS }

	private MEASURE_STATE measureState                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ;

	private View MeasuringView,exceptionView;
	private ManometerView manometerView;
	private TextView pressureValueTV,exceptionMsgTV;
	private Button measureBtn;
	private String mDeviceAddress;
	private Handler handler = new Handler();
	private Dialog readyToMeasureDialog;
	private CustomDialog measureErrorDialog;

	private void showErrorDialog(String errorMessage){
		measureErrorDialog = DialogManager.getMeasureErrorDialog(getActivity(),errorMessage);
		if(measureErrorDialog != null && !measureErrorDialog.isShowing())measureErrorDialog.show();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if(measureErrorDialog != null && measureErrorDialog.isShowing())measureErrorDialog.dismiss();
			}
		},5000);
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_measure_ing);
	}

	@Override
	protected void onStartMeasureCmdSecondTick(int lastSeconds) {
		String str = getString(R.string.starting);
		measureBtn.setText(str + "...".substring(0,lastSeconds % 4));
	}

	@Override
	protected void onStopMeasureCmdSecondTick(int lastSeconds) {
		String str = getString(R.string.stoping);
		measureBtn.setText(str + "...".substring(0,lastSeconds % 4));
	}


	@Override
	protected void measureCmdNotResponsed() {
		setMeasureState(MEASURE_STATE.MEASURE_ANOMALOUS);
	}

	@Override
	protected void onStartMeasureFailed() {
		// 30都没响应可能是连接断开了，所以重新链接试试
		setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
		showErrorDialog(getActivity().getString(R.string.connect_failed_try_to_scan));
		if(readyToMeasureDialog.isShowing()) readyToMeasureDialog.dismiss();
		MeasureDeviceFragment.getInstance().getArgumentBundle().putBoolean("isRescan",true);
		replaceSelfWithFragment(MeasureDeviceFragment.getInstance());
	}

	@Override
	protected void onStopMeasureFailed() {
		// 30都没响应可能是连接断开了，所以重新链接试试
		setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
		showErrorDialog(getActivity().getString(R.string.connect_failed_try_to_scan));
		if(readyToMeasureDialog.isShowing()) readyToMeasureDialog.dismiss();
		MeasureDeviceFragment.getInstance().getArgumentBundle().putBoolean("isRescan",true);
		replaceSelfWithFragment(MeasureDeviceFragment.getInstance());
	}

	@Override
	protected void onValidBLEServiceFound() {
		measureBtn.setEnabled(true);
	}

	@Override
	protected void findView() {
		MeasuringView = findViewById(R.id.measuring_view);
		exceptionView = findViewById(R.id.exception_view);
		pressureValueTV = ((TextView) findViewById(R.id.pressure_value));
		manometerView = (ManometerView) findViewById(R.id.manometer);
		exceptionMsgTV = (TextView) findViewById(R.id.exception_msg);
		measureBtn = (Button) findViewById(R.id.measure_btn);
	}

	@Override
	protected void initView() {
		Bundle bundle = getArgumentBundle();
		mDeviceAddress = bundle.getString("device_address");
		setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
		readyToMeasureDialog = DialogManager.getReadyToMeasureDialog(getActivity());
		measureErrorDialog = DialogManager.getMeasureErrorDialog(getActivity(),getActivity().getString(R.string.connect_failed_try_to_scan));
	}


	@Override
	public void onResume() {
		super.onResume();
		manometerView.setProgress(0);
		pressureValueTV.setText("0");
	}

	@Override
	public void onStop() {
		super.onStop();
		if(readyToMeasureDialog.isShowing()) readyToMeasureDialog.dismiss();
	}

	@Override
	public void onConnectDeviceFailed(String deviceAddress) {
		super.onConnectDeviceFailed(deviceAddress);
		reconnectDevice();
	}
/*
	@Override
	public void onConnectDeviceFailed(String deviceAddress) {
		super.onConnectDeviceFailed(deviceAddress);
		showErrorDialog(getActivity().getString(R.string.connect_failed_try_to_scan));
		MeasureDeviceFragment.getInstance().getArgumentBundle().putBoolean("isRescan",true);
		replaceSelfWithFragment(MeasureDeviceFragment.getInstance());
	}
*/

	@Override
	public void onConnectDeviceSucceeded(String deviceAddress) {
		// 是合法可用的医疗设备
		BLEPreference.getInstance().setBindedDeviceMac(mDeviceAddress);
		setMeasureState(MEASURE_STATE.STARTING_MEASURE);
	}

	private void setMeasureState(MEASURE_STATE measureState){
		if(this.measureState == measureState) return;
		if(measureState == MEASURE_STATE.READY_TO_MEASURE){
			MeasuringView.setVisibility(View.VISIBLE);
			exceptionView.setVisibility(View.GONE);
			measureBtn.setText(R.string.start_measure);
			measureBtn.setEnabled(true);
			measureBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					setMeasureState(MEASURE_STATE.STARTING_MEASURE);
				}
			});
			setMeasureState(MEASURE_STATE.STARTING_MEASURE); // 自动开始
		} else if(measureState == MEASURE_STATE.STARTING_MEASURE){
//			receivedResultData = false;
			startMeasure();
			if(readyToMeasureDialog != null && !readyToMeasureDialog.isShowing()) readyToMeasureDialog.show();
			measureBtn.setEnabled(false);
		}else if(measureState == MEASURE_STATE.MEASURING){
			MeasuringView.setVisibility(View.VISIBLE);
			exceptionView.setVisibility(View.GONE);
			if(readyToMeasureDialog != null) readyToMeasureDialog.dismiss();
			measureBtn.setText(R.string.stop_measure);
			measureBtn.setEnabled(true);
			measureBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					setMeasureState(MEASURE_STATE.STOPING_MEASURE);
				}
			});
		}else if(measureState == MEASURE_STATE.STOPING_MEASURE){
			measureBtn.setEnabled(false);
			stopMeasure();
		}else if(measureState == MEASURE_STATE.MEASURE_ANOMALOUS){
			if(readyToMeasureDialog.isShowing()) readyToMeasureDialog.dismiss();
			MeasuringView.setVisibility(View.GONE);
			exceptionView.setVisibility(View.VISIBLE);
			measureBtn.setText(R.string.measure_again);
			measureBtn.setEnabled(true);
			measureBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
				}
			});
		}
		this.measureState = measureState;
	}

	@Override
	public void onMeasureResultDataError() {
		super.onMeasureResultDataError();
	}

	@Override
	public void onMeasureResultDataReceived(MeasureResult measureResult) {
		super.onMeasureResultDataReceived(measureResult);
		setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
		Bundle bundle = MeasureResultFragment.getInstance().getArgumentBundle();
		bundle.putParcelable("record", RecordEntity.parseFromMeasureResult(getActivity(),measureResult));
		replaceSelfWithFragment(MeasureResultFragment.getInstance());
	}

	@Override
	public void onAckStartMeasure() {
		super.onAckStartMeasure();
		setMeasureState(MEASURE_STATE.MEASURING);
		measureBtn.setText(R.string.start_measure);
	}

	@Override
	public void onAckStopMeasure() {
		super.onAckStopMeasure();
		setMeasureState(MEASURE_STATE.READY_TO_MEASURE);
		measureBtn.setText(R.string.stop_measure);
	}

	@Override
	public void onMeasureExceptionOccurred(@StringRes int msgResId) {
		super.onMeasureExceptionOccurred(msgResId);
		measureBtn.setEnabled(true);
		measureBtn.setText(R.string.measure_again);
		setMeasureState(MEASURE_STATE.MEASURE_ANOMALOUS);
		exceptionMsgTV.setText(msgResId);
	}

	@Override
	public void onReceivedDataButUnrecognized() {
		super.onReceivedDataButUnrecognized();
	}


	@Override
	public void onReceivedPressureData(Pressure pressure) {
		super.onReceivedPressureData(pressure);
		if(measureState == MEASURE_STATE.STARTING_MEASURE) setMeasureState(MEASURE_STATE.MEASURING);
		manometerView.setProgress(pressure.cuffPressure);
		pressureValueTV.setText(pressure.cuffPressure + "");
	}


}
